﻿using System.Linq;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using TextAnalytics.Models;

namespace TextAnalytics.Views
{
    /// <summary>
    /// Interaction logic for WordListView.xaml
    /// </summary>
    public partial class WordListView : UserControl
    {
        public ObservableCollection<WordViewModel> Words { get; set; }

        public class WordViewModel
        {
            public int Rank { get; set; }
            public int Frequency { get; set; }
            public string Text { get; set; }
        }

        public WordListView()
        {
            InitializeComponent();
            Words = new ObservableCollection<WordViewModel>();
            this.DataContext = this;
        }

        private void WordListView_Loaded(object sender, RoutedEventArgs e)
        {
            ProjectService.Default.DidSelectFile += ProjectService_DidSelectFile;
        }

        void ProjectService_DidSelectFile(ProjectService sender, SelectFileEventArgs args)
        {
            var text = sender.GetSelectedFileContent();
            if (string.IsNullOrEmpty(text)) return;

            var splitResult = TextSplitter.Default.Split(text);
            Words.Clear();

            var words = splitResult.Words.Select(x => new WordViewModel() { Text = x.Value.Text, Frequency = x.Value.Occurrences.Count })
                                        .OrderByDescending(x => x.Frequency);

            var i = 1;
            foreach (var word in words)
            {
                word.Rank = i++;
                Words.Add(word);
            }
            
        }
    }
}
